import React, { useState, useEffect, useRef } from 'react';
import './AIModal.css';
import { Modal, Input, Button, message } from 'antd';

import { API_BASE_URL_MESSAGE } from '../utils/config';

interface AIModalProps {
  isVisible: boolean;
  onClose: () => void;
  message: string;
  messageType: string;
}

const AIModal: React.FC<AIModalProps> = ({
  isVisible,
  onClose,
  message,
  messageType,
}) => {
  const [aiResponse, setAiResponse] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [isStreaming, setIsStreaming] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [streamingText, setStreamingText] = useState('');
  const [fullResponse, setFullResponse] = useState('');
  const streamingRef = useRef<NodeJS.Timeout | null>(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  // 流式输出函数
  const startStreamingOutput = (text: string) => {
    // 清除之前的定时器
    if (streamingRef.current) {
      clearTimeout(streamingRef.current);
      streamingRef.current = null;
    }

    setIsStreaming(true);
    setIsPaused(false);
    setStreamingText('');
    setFullResponse(text);

    // 开始流式输出
    let currentIndex = 0;

    const streamText = () => {
      if (currentIndex < text.length && !isPaused) {
        setStreamingText(text.substring(0, currentIndex + 1));
        currentIndex++;
        streamingRef.current = setTimeout(streamText, 30);
      } else if (currentIndex >= text.length) {
        setIsStreaming(false);
        setAiResponse(text);
        streamingRef.current = null;
      }
    };

    streamText();
  };

  // 暂停/继续流式输出
  const toggleStreaming = () => {
    if (isStreaming) {
      if (isPaused) {
        // 继续流式输出
        setIsPaused(false);
        const currentLength = streamingText.length;
        if (currentLength < fullResponse.length) {
          let currentIndex = currentLength;

          const streamText = () => {
            if (currentIndex < fullResponse.length) {
              setStreamingText(fullResponse.substring(0, currentIndex + 1));
              currentIndex++;
              streamingRef.current = setTimeout(streamText, 30);
            } else if (currentIndex >= fullResponse.length) {
              setIsStreaming(false);
              setAiResponse(fullResponse);
              streamingRef.current = null;
            }
          };

          streamText();
        }
      } else {
        // 暂停流式输出
        setIsPaused(true);
        if (streamingRef.current) {
          clearTimeout(streamingRef.current);
          streamingRef.current = null;
        }
      }
    }
  };

  // 停止流式输出
  const stopStreaming = () => {
    if (streamingRef.current) {
      clearTimeout(streamingRef.current);
      streamingRef.current = null;
    }
    setIsStreaming(false);
    setIsPaused(false);
    setStreamingText('');
  };

  // AI API调用函数
  const getAIResponse = async (question: string) => {
    setIsLoading(true);
    setError('');
    setAiResponse('');
    setStreamingText('');
    setFullResponse('');

    // 创建AbortController用于取消请求
    abortControllerRef.current = new AbortController();

    try {
      // 根据消息类型构建不同的AI请求
      const requestBody: any = { question: question };

      // 根据消息类型设置不同的模式
      if (messageType === 'image') {
        requestBody.mode = 'image_question_answer';
      } else if (messageType === 'file') {
        requestBody.mode = 'file_homework_correction';
      } else {
        requestBody.mode = 'text_question_answer';
      }

      const response = await fetch(`${API_BASE_URL_MESSAGE}/ysx/api/ask`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(requestBody),
        signal: abortControllerRef.current.signal,
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();

      if (data.answer) {
        // 开始流式输出
        startStreamingOutput(data.answer);
      } else {
        setAiResponse('抱歉，AI服务暂时无法回答，请稍后重试。');
      }
    } catch (error: any) {
      if (error.name === 'AbortError') {
        console.log('AI请求已取消');
        return;
      }
      console.error('AI回答失败:', error);
      setError('抱歉，AI回答生成失败，请重试。错误信息：' + error.message);
    } finally {
      setIsLoading(false);
    }
  };

  // 当弹窗显示时自动调用AI
  useEffect(() => {
    if (isVisible && message) {
      getAIResponse(message);
    }
  }, [isVisible, message]);

  // 清理函数
  useEffect(() => {
    return () => {
      // 清理定时器
      if (streamingRef.current) {
        clearTimeout(streamingRef.current);
      }
      // 取消请求
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  // 复制AI回答到剪贴板
  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(aiResponse);
      alert('AI回答已复制到剪贴板！');
    } catch (error) {
      console.error('复制失败:', error);
      alert('复制失败，请手动选择文本复制');
    }
  };

  // 格式化AI回答文本
  const formatAIResponse = (text: string) => {
    // 处理换行
    const lines = text.split('\n');
    return lines.map((line, index) => (
      <p key={index} className="ai-response-line">
        {line}
      </p>
    ));
  };

  if (!isVisible) return null;

  return (
    <div className="ai-modal-overlay" onClick={onClose}>
      <div className="ai-modal-container" onClick={e => e.stopPropagation()}>
        {/* 弹窗头部 */}
        <div className="ai-modal-header">
          <div className="ai-modal-title">
            <span className="ai-icon">🤖</span>
            <span>AI智能回答</span>
          </div>
          <button className="ai-modal-close" onClick={onClose}>
            ✕
          </button>
        </div>

        {/* 原始消息显示 */}
        <div className="ai-modal-original-message">
          <div className="original-message-section">
            <div className="original-message-label">原始消息：</div>
            <div className="original-message-content">
              {messageType === 'image' && (
                <span className="message-type-tag">📷 图片</span>
              )}
              {messageType === 'file' && (
                <span className="message-type-tag">📄 文件</span>
              )}
              {messageType === 'location' && (
                <span className="message-type-tag">📍 位置</span>
              )}
              {messageType === 'voice' && (
                <span className="message-type-tag">🎤 语音</span>
              )}
              {messageType === 'video' && (
                <span className="message-type-tag">🎥 视频</span>
              )}
              <span className="message-text">{message}</span>
            </div>
          </div>

          {/* 流式输出控制按钮区域 */}
          <div className="streaming-controls-section">
            {isStreaming && (
              <div className="streaming-controls">
                <button className="ai-pause-btn" onClick={toggleStreaming}>
                  {isPaused ? '▶️ 继续' : '⏸️ 暂停'}
                </button>
                <button className="ai-stop-btn" onClick={stopStreaming}>
                  ⏹️ 停止
                </button>
              </div>
            )}
          </div>
        </div>

        {/* AI回答区域 */}
        <div className="ai-modal-content">
          {isLoading && (
            <div className="ai-loading">
              <div className="ai-loading-spinner"></div>
              <div className="ai-loading-text">AI正在思考中...</div>
            </div>
          )}

          {error && (
            <div className="ai-error">
              <div className="ai-error-icon">⚠️</div>
              <div className="ai-error-text">{error}</div>
              <button
                className="ai-retry-btn"
                onClick={() => getAIResponse(message)}
              >
                重试
              </button>
            </div>
          )}

          {(aiResponse || streamingText) && !isLoading && !error && (
            <div className="ai-response">
              <div className="ai-response-content">
                {isStreaming ? (
                  <div className="streaming-content">
                    {formatAIResponse(streamingText)}
                    <span className="streaming-cursor">|</span>
                  </div>
                ) : (
                  formatAIResponse(aiResponse)
                )}
              </div>
              <div className="ai-response-actions">
                {!isStreaming && (
                  <>
                    <button className="ai-copy-btn" onClick={copyToClipboard}>
                      📋 复制回答
                    </button>
                    <button
                      className="ai-regenerate-btn"
                      onClick={() => getAIResponse(message)}
                    >
                      🔄 重新生成
                    </button>
                  </>
                )}
              </div>
            </div>
          )}
        </div>

        {/* 弹窗底部 */}
        <div className="ai-modal-footer">
          <div className="ai-modal-tips">
            💡 提示：AI回答仅供参考，请结合实际情况判断
          </div>
        </div>
      </div>
    </div>
  );
};

export default AIModal;
